package com.roc.web.action.profit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.dao.DaoException;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitDetail;
import com.roc.service.IExcelExportService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.service.profit.IProfitService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/profit")
public class ProfitSumQueryAction  extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(ProfitSumQueryAction.class);
	private ProfitSumQuerySearchCondition searchCondition;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Autowired
	private IProfitService profitService;
	@Autowired
	private IExcelExportService excelExportService;
	
	private InputStream excelFile;
	private String excelName;
	
	@Action(value = "initProfitSummarize", results = {@Result(name = "success", location = "/pages/profit/profitSummarize.jsp") })
	public String initProfitDetail() throws ServiceException{
		init();
		return SUCCESS;
	}
	
	private void init()throws ServiceException{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map map= new HashMap();
		try{
			//根据登录人角色显示不同代理商
			Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
			String superRole= mapReal.get("superRole");
            String opRealId =mapReal.get("opRealId");
            String oneOrgCode=logingOperators.getOneagentid();//机构
            /*//代理商、业务员
			if(Role.AGENT.getCode().equals(superRole)||Role.AGENT_BUSS.getCode().equals(superRole)||Role.MERCHANT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
				 map =  profitService.getOpertorsIdsTreeById(Long.parseLong(opRealId));
			}
			else*/ 
            //销售
            if(Role.MARKET_DIRECT.getCode().equals(superRole)||Role.MARKET_LEAD.getCode().equals(superRole)){
				 map =  profitService.getDirectlyAgentIdsTreeByRealId(Long.parseLong(opRealId));
			}//其他
			else{
				 map =  profitService.getOpertorsIdsTreeById(Long.parseLong(opRealId));
			}
			getRequest().setAttribute("agnetList",map);
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
	}
	
	@Action(value = "queryProfitSummarize", results = { 
			@Result(name = "success", location = "/pages/profit/profitSummarize.jsp"),
            @Result(name="error",location="/pages/profit/profitSummarize.jsp"),
            @Result(name="login",location="/pages/profit/profitSummarize.jsp") })

	public String queryProfitSummarize() throws ServiceException, DaoException{
	/*	Operators loginMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);*/
		init();
		if(searchCondition==null){
			searchCondition=(ProfitSumQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ProfitSumQuerySearchCondition();
			}
		}
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(-1==searchCondition.getId()){
				logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
	            String superRole= mapReal.get("superRole");
	            String opRealId =mapReal.get("opRealId");
				long id=1;
				String ids = null;
				//代理商、业务员
				if(Role.AGENT.getCode().equals(superRole)||Role.AGENT_BUSS.getCode().equals(superRole)||Role.MERCHANT.getCode().equals(superRole)||Role.SFB_AGENT.getCode().equals(superRole)){
					 id=Long.parseLong(opRealId);
				}//销售
				else if(Role.MARKET_DIRECT.getCode().equals(superRole)||Role.MARKET_LEAD.getCode().equals(superRole)){
				 ids =  profitService.getOpertorsScIdById(Long.parseLong(opRealId));
				}//管理员
				else{
				 ids =  profitService.getOpertorsIdsById(Long.parseLong(opRealId));
				}
				searchCondition.setIds(ids);
				searchCondition.setId(id);
				
			}		
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			//searchRsList=pagenitionService.findAllSQL(searchCondition, 0, 9999999);
			
			BigDecimal merfeesum=new BigDecimal("0");
			dealWithTheListSpecially(searchRsList);
			Iterator iterator=searchRsList.iterator();
			while(iterator.hasNext()){
				ProfitDetail prof=(ProfitDetail) iterator.next();
				merfeesum=merfeesum.add(prof.getMerfee().multiply(prof.getPercent()));
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			//this.setTotalPage(this.calcuTotalPage(1));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("totalNumTotal", merfeesum.toPlainString());
			setSearchToConditionSession(searchCondition);
		
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError("分润汇总查询失败");
			
		}
		return SUCCESS;
	}
	
	
	
	@Action(value="exportProfitSummarize",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=\"${excelName}\"",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/profit/profitSummarize.jsp") })
	public String exportProfitSummarize() throws Exception{
			Operators operators=profitService.loadById(searchCondition.getId());
			String temp="";
			if(null ==operators){
				 temp =searchCondition.getBeginTime()+"至"+searchCondition.getEndTime()+"的分润.xls";	
			}else{
				 temp = operators.getRealName()+"--"+searchCondition.getBeginTime()+"至"+searchCondition.getEndTime()+"的分润.xls";	
			}
			excelName=new String(temp.getBytes(),"ISO8859-1");
			if(searchCondition==null){
				searchCondition=(ProfitSumQuerySearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new ProfitSumQuerySearchCondition();
				}
			}
			try {
				searchRsList=pagenitionService.findAllSQL(searchCondition, 0, 9999999);
				dealWithTheListSpecially(searchRsList);
				String transDate=searchCondition.getBeginTime().substring(0, 6);
				SXSSFWorkbook work=excelExportService.exportProfit(operators, searchRsList, transDate);
	
				 ByteArrayOutputStream output = new ByteArrayOutputStream();  
				         work.write(output);  
				   
				        byte[] ba = output.toByteArray();  
				         excelFile = new ByteArrayInputStream(ba);  
				         output.flush();  
						         output.close();  
						
			}catch (ServiceException e) {
				e.printStackTrace();
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
				
			}
		return SUCCESS;
	}


	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		// TODO Auto-generated method stub
		List<ProfitDetail> tempList=new ArrayList<ProfitDetail>();
		try {
			if(list!=null&&list.size()>0){
					Iterator iterator=list.iterator();
					while(iterator.hasNext()){
						ProfitDetail prof=new ProfitDetail();
							/*Object[] obj=(Object[]) iterator.next();
							prof.setAgentName(Constance.Null2EmptyTrim(obj[0]));
							String cardClass=Constance.Null2EmptyTrim(obj[1]);
							if("00".equals(cardClass)){
								prof.setCardClass("信用卡");
							}else{
								prof.setCardClass("借记卡");
							}
							
							String prodCd=Constance.Null2EmptyTrim(obj[2]);
							if("04".equals(prodCd)){
								prof.setProdCd("D0实时交易");
							}else{
								prof.setProdCd("标准类T1交易");
							}
							
							double amt=Double.parseDouble(Constance.null2Amt(obj[3]));
							if(amt>=0){
								prof.setSAmt(amt);
							}else{
								prof.setSAmt(0);
							}
							
							double merfee=Double.parseDouble(Constance.null2Amt(obj[4]));
							if(merfee>=0){
								prof.setMerfee(merfee);
							}else{
								prof.setMerfee(0);
							}
							prof.setTCount(Constance.Null2EmptyTrim(obj[5]));
							prof.setCreateDate(Constance.Null2EmptyTrim(obj[6]));*/
						
						Object[] obj=(Object[]) iterator.next();
						prof.setAgentName(Constance.Null2EmptyTrim(obj[0]));
						prof.setCardClass(Constance.Null2EmptyTrim(obj[1]));
						prof.setProdCd(Constance.Null2EmptyTrim(obj[2]));
						prof.setSAmt(new BigDecimal(Constance.null2Amt(obj[3])));
						prof.setMerfee(new BigDecimal(Constance.null2Amt(obj[4])));
						prof.setTCount(Constance.Null2EmptyTrim(obj[5]));
						prof.setCreateDate(Constance.Null2EmptyTrim(obj[6]));
						prof.setAccountNo(Constance.Null2EmptyTrim(obj[7]));
							tempList.add(prof);
						
					}
				}
			searchRsList=this.dealProfitSummary(tempList);
		} catch (Exception e) {
			logger.error("数据处理异常"+e.getMessage(),e);
		}
	}

	
	/**
	 * 计算实际分润金额
	 * @throws ServiceException 
	 */
	public List<Object> dealProfitSummary(List<ProfitDetail> list) throws ServiceException {
		List<Object> restList= new ArrayList<Object>();
		Map<String,BigDecimal> map = new HashMap<String,BigDecimal>();
		BigDecimal transAmt = new BigDecimal(0);

		for (ProfitDetail pro : list) {
			if(map.containsKey(pro.getAccountNo())){
				transAmt=map.get(pro.getAccountNo());
				transAmt = transAmt.add(pro.getSAmt());
				map.put(pro.getAccountNo(), transAmt);
			}else{
				transAmt = transAmt.add(pro.getSAmt());
				map.put(pro.getAccountNo(), transAmt);
			}
		}
		Map<String,BigDecimal> mapPercent = new HashMap<String,BigDecimal>();
		for(Map.Entry<String, BigDecimal> entry : map.entrySet())   
		{   
			String perStr = profitService.getProfitPercent(entry.getKey(), entry.getValue());
			mapPercent.put(entry.getKey(), new BigDecimal(perStr));
		   
		} 
		
		// 统计分润金额
		for (ProfitDetail pro : list) {
			BigDecimal profitAmt = pro.getMerfee();
			BigDecimal percent = mapPercent.get(pro.getAccountNo());
			pro.setPercent(percent);
			pro.setRealMerfee(profitAmt.multiply(percent));
			restList.add(pro);
		}

		return restList;
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_PROFIT_DETAIL_QUERY);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_PROFIT_DETAIL_QUERY, searchCondition);
	}

	public ProfitSumQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ProfitSumQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}
	public String getExcelName() {
		return excelName;
	}



}
